package com.example.coffee.slice;
import com.example.coffee.ResourceTable;
import com.example.coffee.items.CaffeeItem;
import com.example.coffee.mock.DataMockManager;
import com.example.coffee.provider.ContentListDataProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.TextField;

import java.util.List;

public class SearchSlice extends AbilitySlice {
    // 组件实例
    private TextField searchTextField = null;
    private Button searchButton = null;
    private ListContainer resultList = null;
    // 数据源
    private List<CaffeeItem> dataList = null;
    // Porvider对象
    private ContentListDataProvider provider;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_search_slice);
        // 初始化
        findComponent();
    }
    // 进行初始化
    private void findComponent() {
        // 获取组件实例
        searchTextField = (TextField) findComponentById(ResourceTable.Id_search_field);
        searchButton = (Button) findComponentById(ResourceTable.Id_search_button_real);
        resultList = (ListContainer) findComponentById(ResourceTable.Id_searcg_result_list);
        // 搜索按钮的点击交互事件监听
        searchButton.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                // 点击搜索时，先收起键盘
                searchTextField.clearFocus();
                // 获取输入框的内容
                String keyString = searchTextField.getText();
                // 检查要搜索的关键字是否合法
                if (keyString != null && keyString.length() > 0) {
                    // 生成模拟数据
                    dataList = DataMockManager.mockSearchResultList(keyString);
                    // 重设列表数据源
                    provider.setDataList(dataList);
                    // 刷新列表
                    provider.notifyDataChanged();
                }
            }
        });
        // 创建列表Provider并绑定到列表
        provider = new ContentListDataProvider(dataList, this);
        resultList.setItemProvider(provider);
        // 预留列表的点击事件，后续处理跳转到详情页
        resultList.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                // 处理跳转到详情页的逻辑
                CaffeeItem item = dataList.get(i);
                Intent intent = new Intent();
                intent.setParam("image", item.getImageId());
                intent.setParam("name", item.getName());
                intent.setParam("description", item.getDescription());
                intent.setParam("price", item.getPrice());
                intent.setParam("originalPrice", item.getOriginalPrice());
                present(new DetailSlice(), intent);
            }
        });
    }
}
